﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace BookSourceVerification.handlers;

public class DelDoubleHandler : IHandler<JObject>
{
    // todo 2024年7月18日 21:40:54 这个集合可能存在书源过多导致 urls 集合存储过多集合占用内存的问题
    private readonly HashSet<string> _urls = new();

    public bool IsChecked(JObject node, HandlerResult result)
    {
        if (result.Data is string) return true;
        result.Fail();
        return false;
    }

    public Task DoHandler(JObject node, HandlerResult result)
    {
        string url = (result.Data as string)!;
        lock (_urls)
        {
            if (!_urls.Add(url))
            {
                result.Fail();
                return Task.CompletedTask;
            }
        }

        result.Success(url);
        return Task.CompletedTask;
    }

    public void AfterHandler()
    {
        if (this._urls.Count > 0)
        {
            lock (this._urls)
            {
                if (this._urls.Count > 0)
                {
                    this._urls.Clear();
                }
            }
        }
    }
}